package com.zlx.sharelive.activity;

import android.content.Intent;
import android.media.MediaMetadataRetriever;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.webkit.URLUtil;
import android.widget.ImageView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.zlx.module_base.base_ac.BaseAc;
import com.zlx.module_base.base_api.res_data.VideoPurchaseListBean;
import com.zlx.module_base.base_api.util.ApiUtil;
import com.zlx.module_base.base_util.SPUtil;
import com.zlx.module_network.api1.livedata.BaseObserver;
import com.zlx.module_network.api1.livedata.BaseObserverCallBack;
import com.zlx.module_network.bean.ApiResponse;
import com.zlx.sharelive.R;
import com.zlx.sharelive.adapter.CommonRecyclerViewAdapter;
import com.zlx.sharelive.adapter.CommonRecyclerViewHolder;
import com.zlx.sharelive.utils.GlideImgManager;
import com.zlx.sharelive.utils.StringUt;

import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 已购影片
 */
public class PurchasedVideoAc extends BaseAc {

    @BindView(R.id.rv_data)
    RecyclerView rv_data;
    @BindView(R.id.sw_layout)
    SwipeRefreshLayout sw_layout;

    private int page = 1;
    private List<VideoPurchaseListBean.InfoDTO.RecordsDTO> mList = new ArrayList<>();
    private CommonRecyclerViewAdapter<VideoPurchaseListBean.InfoDTO.RecordsDTO> mAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.ac_purchased_video;
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    mAdapter.notifyItemChanged(msg.arg1);
                    break;
            }
        }
    };


    @Override
    public void initViews() {
        super.initViews();

        getVideoPurchaseList(page);
        initRecyclerView();

        sw_layout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                getVideoPurchaseList(page);
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();

        page = 1;
        getVideoPurchaseList(page);
    }

    /**
     * 视频购买记录
     *
     * @param page
     */
    private void getVideoPurchaseList(int page) {
        ApiUtil.getVideoApi().getVideoPurchaseList(SPUtil.getToken(this),
                String.valueOf(page)).observe(this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<VideoPurchaseListBean>>() {
            @Override
            public void onSuccess(ApiResponse<VideoPurchaseListBean> data) {
                sw_layout.setRefreshing(false);
                mList.clear();
                if (null != data) {
                    if (null != data.getData()) {
                        if (null != data.getData().getInfo()) {
                            if (data.getData().getInfo().size() > 0) {
                                if (null != data.getData().getInfo().get(0).getRecords()) {
                                    if (data.getData().getInfo().get(0).getRecords().size() > 0) {
                                        mList.addAll(data.getData().getInfo().get(0).getRecords());
                                    } else {
                                        //显示无数据页面
                                    }
                                }
                            }
                        }
                    }
                }
                mAdapter.notifyDataSetChanged();

                for (int i = 0; i < mList.size(); i++) {
                    final String video = mList.get(i).getVideo();
                    final int position = i;
                    new Thread() {
                        @Override
                        public void run() {
                            super.run();
                            if (!StringUt.isEmpty(video)) {
                                if (isValid(video) == true) {
                                    if (!StringUt.isEmpty(getPlayTime(video))) {
                                        String time = getFormatedDateTime("mm:ss", Long.valueOf(getPlayTime(video)));
                                        mList.get(position).setPeriod(time);
                                        Message msg = new Message();
                                        msg.what = 1;
                                        msg.arg1 = position;
                                        handler.sendMessage(msg);
                                    }
                                }
                            }
                        }
                    }.start();
                }
            }
        }));
    }


    private void initRecyclerView() {
        rv_data.setLayoutManager(new LinearLayoutManager(this));

        mAdapter = new CommonRecyclerViewAdapter<VideoPurchaseListBean.InfoDTO.RecordsDTO>(this, mList) {
            @Override
            public void convert(CommonRecyclerViewHolder holder, VideoPurchaseListBean.InfoDTO.RecordsDTO entity, int position) {

                GlideImgManager.glideLoader(PurchasedVideoAc.this, entity.getCover(), holder.getView(R.id.iv_recommend), 1);

                GlideImgManager.glideLoader(PurchasedVideoAc.this, entity.getAvatar(), holder.getView(R.id.iv_recommend_head), 0);

                holder.setText(R.id.tv_recommend_title, entity.getTitle());

                holder.setText(R.id.tv_recommend_nickname, entity.getNickname());

                holder.setText(R.id.tv_time, entity.getPeriod());

                if (entity.getIsLike().equals("1")) {
                    ((ImageView) holder.getView(R.id.iv_fabulous)).setImageResource(R.mipmap.fabulous_img_true);
                } else {
                    ((ImageView) holder.getView(R.id.iv_fabulous)).setImageResource(R.mipmap.fabulous_img2);
                }

                if (entity.getIsVip().equals("1")) {
                    ((ImageView) holder.getView(R.id.iv_vip)).setVisibility(View.VISIBLE);
                } else {
                    ((ImageView) holder.getView(R.id.iv_vip)).setVisibility(View.GONE);
                }
                if (!StringUt.isEmpty(entity.getAuthentication())) {
                    if (entity.getAuthentication().equals("1")) {
                        ((ImageView) holder.getView(R.id.iv_goddess)).setVisibility(View.VISIBLE);
                    } else {
                        ((ImageView) holder.getView(R.id.iv_goddess)).setVisibility(View.GONE);
                    }
                }
                holder.setText(R.id.tv_pageViews, entity.getPageViews());
                holder.setText(R.id.tv_fabulous, entity.getLikeCount());
                holder.setText(R.id.tv_comment_count, entity.getCommentCount());
            }

            @Override
            public int getLayoutViewId(int viewType) {
                return R.layout.item_long_video;
            }
        };

        rv_data.setAdapter(mAdapter);

        mAdapter.setOnRecyclerViewItemClickListener(new CommonRecyclerViewAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                startActivity(new Intent(PurchasedVideoAc.this, VideoDetailsAc.class)
                        .putExtra("id", mList.get(position).getId())
                        .putExtra("title", mList.get(position).getTitle()));
            }
        });
    }

    @OnClick(R.id.iv_back)
    public void setOnClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
        }
    }

    private String getPlayTime(String mUri) {
        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
        String duration = "";
        try {
            if (mUri != null) {
                HashMap headers = null;
                if (headers == null) {
                    headers = new HashMap();
                    headers.put("User-Agent", "Mozilla/5.0 (Linux; U; Android 4.4.2; zh-CN; MW-KW-001 Build/JRO03C) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 UCBrowser/1.0.0.001 U4/0.8.0 Mobile Safari/533.1");
                }
                mmr.setDataSource(mUri, headers);
            } else {
                //mmr.setDataSource(mFD, mOffset, mLength);
            }
            //注意地址 mUri= /storage/emulated/0/youshixiu/rectools/录屏专家190629113518.mp4    本地
            duration = mmr.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_DURATION);//时长(毫秒)
            String width = mmr.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);//宽
            String height = mmr.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);//高
        } catch (Exception ex) {
            Log.e("TAG", "MediaMetadataRetriever exception " + ex);
        } finally {
            mmr.release();
        }
        return duration;
    }

    public static String getFormatedDateTime(String pattern, long dateTime) {
        SimpleDateFormat sDateFormat = new SimpleDateFormat(pattern);
        return sDateFormat.format(new Date(dateTime + 0));
    }


    private boolean isValid(String urlString) {
        try {
            URL url = new URL(urlString);
            return URLUtil.isValidUrl(urlString) && Patterns.WEB_URL.matcher(urlString).matches();
        } catch (MalformedURLException e) {

        }
        return false;
    }
}
